<template>
  <div class="keyboard">
    <div class="keyboard-row">
      <span v-for="key in firstRow" :key="key" :style="{ backgroundColor: getFingerClass(key) }"
        :class="[{ active: isKeyPressed(key) }]">
        {{ key.toUpperCase() }}
      </span>
    </div>
    <div class="keyboard-row">
      <span v-for="key in secondRow" :key="key" :style="{ backgroundColor: getFingerClass(key) }"
        :class="{ active: isKeyPressed(key) }">
        {{ key.toUpperCase() }}
      </span>
    </div>
    <div class="keyboard-row">
      <span v-for="key in thirdRow" :key="key" :style="{ backgroundColor: getFingerClass(key) }"
        :class="[{ active: isKeyPressed(key) }]">
        {{ key.toUpperCase() }}
      </span>
    </div>
    <div class="keyboard-row">
      <span v-for="key in fourthRow" :key="key" :style="{ backgroundColor: getFingerClass(key) }"
        :class="[{ active: isKeyPressed(key) }]">
        {{ key.toUpperCase() }}
      </span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
// @ts-ignore
import { getFingerClass } from '@/utils/fingerColors'
import '@/assets/styles/fingerColors.css' // 确保 CSS 正确导入

// 键盘行布局
const firstRow = ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p']
const secondRow = ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l']
const thirdRow = ['z', 'x', 'c', 'v', 'b', 'n', 'm']
const fourthRow = ['space']

// 存储按下的键
const pressedKeys = ref(new Set<string>())

// 键盘按下时点亮按键
const handleKeyDown = (event: KeyboardEvent) =>
{
  if (event.key == ' ')
  {
    pressedKeys.value.add('space')
    return
  }
  pressedKeys.value.add(event.key.toLowerCase())
}

// 键盘抬起时恢复按键
const handleKeyUp = (event: KeyboardEvent) =>
{
  if (event.key == ' ')
  {
    pressedKeys.value.delete('space')
    return
  }
  pressedKeys.value.delete(event.key.toLowerCase())
}

// 检查某个按键是否处于按下状态
const isKeyPressed = (key: string) =>
{
  return pressedKeys.value.has(key.toLowerCase())
}

// 在组件挂载和卸载时监听键盘事件
onMounted(() =>
{
  window.addEventListener('keydown', handleKeyDown)
  window.addEventListener('keyup', handleKeyUp)
})

onUnmounted(() =>
{
  window.removeEventListener('keydown', handleKeyDown)
  window.removeEventListener('keyup', handleKeyUp)
})
</script>

<style scoped>
.keyboard {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20px;
}

.keyboard-row {
  display: flex;
  justify-content: center;
  margin: 5px 0;
}

.keyboard-row span {
  font-size: 24px;
  margin: 0 5px;
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 4px;
  min-width: 40px;
  text-align: center;
  transition: background-color 0.2s;
}

/* 按键点亮效果 */
.keyboard-row span.active {
  background-color: #ffcc00;
  color: #fff;
}

/* Import the finger colors */
/* @import '@/assets/styles/fingerColors.css'; */
</style>
